import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/api/graphql/file_gql.dart';
import 'package:labcloud_app/data/user.dart';
import 'package:path/path.dart' as path;
import 'dart:math';

import '../../api/graphql_config.dart';
import '../../config/token_storage.dart';

class Register extends StatefulWidget {
  const Register({super.key});

  @override
  State<Register> createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  // 控制器
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final TextEditingController _nicknameController = TextEditingController();

  // 头像相关
  File? _avatarImage;
  final ImagePicker _picker = ImagePicker();

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _emailController.dispose();
    _confirmPasswordController.dispose();
    _nicknameController.dispose();
    super.dispose();
  }

  // 选择头像图片
  void _pickAvatarImage() async {
    try {
      // 弹出选项让用户选择图片来源
      showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: const Icon(Icons.photo_library),
                  title: const Text('从相册选择'),
                  onTap: () async {
                    Navigator.pop(context);
                    _pickImageFromGallery();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () async {
                    Navigator.pop(context);
                    _pickImageFromCamera();
                  },
                ),
              ],
            ),
          );
        },
      );
    } catch (e) {
      print('选择图片失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片失败: $e')),
      );
    }
  }

  // 从相册选择图片
  void _pickImageFromGallery() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );

      if (pickedFile != null) {
        setState(() {
          _avatarImage = File(pickedFile.path);
        });
      }
    } catch (e) {
      print('从相册选择图片失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片失败: $e')),
      );
    }
  }

  // 拍照选择图片
  void _pickImageFromCamera() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
      );

      if (pickedFile != null) {
        setState(() {
          _avatarImage = File(pickedFile.path);
        });
      }
    } catch (e) {
      print('拍照失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('拍照失败: $e')),
      );
    }
  }

  // 生成随机图片名称
  String _generateRandomImageName({
    String prefix = 'avatar',
    String extension = 'jpg',
  }) {
    final random = Random();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final randomNum = random.nextInt(1000000);
    return '$prefix${timestamp}_$randomNum.$extension';
  }

  // 注册逻辑
  Future<void> _register(
      {File? avatar,
      required String nickname,
      required String username,
      required String password,
      required String email}) async {
    final userModel = Provider.of<UserModel>(context, listen: false);
    
    // 获取GraphQL客户端
    final client = GraphQLProvider.of(context).value;
    
    String? avatarName = 'default.png';
    if (avatar != null) {
      // 获取原文件扩展名，如果没有则默认使用jpg
      String fileExtension = path.extension(avatar.path).replaceAll('.', '');
      if (fileExtension.isEmpty) fileExtension = 'jpg';

      // 生成随机文件名
      avatarName = _generateRandomImageName(
        prefix: 'avatar_',
        extension: fileExtension,
      );
      print('Generated avatar name: $avatarName'); // 输出生成的文件名
      
      final uploadLinkResult = await client.mutate(
        MutationOptions(
          document: gql(FileGQL.fetchUploadLink),
          variables: {
            'bucketName': 'user-avatar',
            'objectName': avatarName,
          },
        ),
      );

      if (uploadLinkResult.hasException) {
        final errorMessage = '获取上传链接失败: ${uploadLinkResult.exception.toString()}';
        print('注册错误: $errorMessage'); // 打印到日志
        throw Exception(errorMessage);
      }

      String uploadUrl = uploadLinkResult.data!['file']['getFileUploadUrl']['url'];
      print(uploadUrl);
      
      // 上传文件
      final request = await HttpClient().putUrl(Uri.parse(uploadUrl));
      request.headers.set('Content-Type', 'image/$fileExtension');
      request.headers.set('Content-Length', await avatar.length());
      final fileBytes = await avatar.readAsBytes();
      request.add(fileBytes);
      final response = await request.close();
      if (response.statusCode != 200) {
        final errorMessage = '文件上传失败，状态码: ${response.statusCode}';
        print('注册错误: $errorMessage'); // 打印到日志
        throw Exception(errorMessage);
      }
    }

    // 执行注册
    final result = await client.mutate(
      MutationOptions(
        document: gql(UserGQL.fetchRegisterUser),
        variables: {
          'nickname': nickname,
          'avatarAddr': 'user-avatar:$avatarName',
          'username': username,
          'password': password,
          'email': email,
        },
      ),
    );

    if (result.hasException) {
      final errorMessage = '注册失败: ${result.exception.toString()}';
      print('注册错误: $errorMessage'); // 打印到日志
      throw Exception(errorMessage);
    }

    final user = User.fromJson(result.data!['user']['registerUser']);
    // 保存token
    TokenStorage.saveTokens(user.accessToken!, user.refreshToken!);
    user.refreshToken = '';
    user.accessToken = '';
    userModel.setUser(user);
    await userModel.saveUserToStorage(); // 保存到持久化存储
  }

  // 注册处理
  void _handleRegister() async {
    if (_nicknameController.text.isEmpty ||
        _usernameController.text.isEmpty ||
        _emailController.text.isEmpty ||
        _passwordController.text.isEmpty ||
        _confirmPasswordController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请填写所有必填项')),
      );
      return;
    }

    if (_passwordController.text != _confirmPasswordController.text) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('两次输入的密码不一致')),
      );
      return;
    }

    // 显示加载提示
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );

    try {
      // 调用注册API
      await _register(
        nickname: _nicknameController.text.trim(),
        username: _usernameController.text.trim(),
        password: _passwordController.text.trim(),
        email: _emailController.text.trim(),
        avatar: _avatarImage,
      );

      // 隐藏加载提示
      Navigator.of(context).pop();

      // 注册成功后返回上一页
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('注册成功')),
      );
      Navigator.of(context).pop(true);
    } catch (e) {
      // 隐藏加载提示
      Navigator.of(context).pop();

      print('注册错误: $e'); // 打印到日志
      // 注册失败
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('注册失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注册'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 头像选择区域
            GestureDetector(
              onTap: _pickAvatarImage,
              child: CircleAvatar(
                radius: 50,
                backgroundColor: Colors.grey[200],
                child: _avatarImage != null
                    ? CircleAvatar(
                        radius: 50,
                        backgroundImage: FileImage(_avatarImage!),
                      )
                    : const Icon(
                        Icons.camera_alt,
                        size: 50,
                        color: Colors.grey,
                      ),
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              '点击选择头像',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 20),
            // 昵称名输入框
            TextField(
              controller: _nicknameController,
              decoration: const InputDecoration(
                labelText: '昵称',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                ),
                prefixIcon: Icon(Icons.person),
              ),
            ),
            const SizedBox(height: 20),

            // 用户名输入框
            TextField(
              controller: _usernameController,
              decoration: const InputDecoration(
                labelText: '用户名',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                ),
                prefixIcon: Icon(Icons.person),
              ),
            ),
            const SizedBox(height: 20),

            // 邮箱输入框
            TextField(
              controller: _emailController,
              decoration: const InputDecoration(
                labelText: '邮箱',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                ),
                prefixIcon: Icon(Icons.email),
              ),
            ),
            const SizedBox(height: 20),

            // 密码输入框
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '密码',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                ),
                prefixIcon: Icon(Icons.lock),
              ),
            ),
            const SizedBox(height: 20),

            // 确认密码输入框
            TextField(
              controller: _confirmPasswordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '确认密码',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                ),
                prefixIcon: Icon(Icons.lock),
              ),
            ),
            const SizedBox(height: 30),

            // 注册按钮
            _buildActionButton('注册', _handleRegister),
            const SizedBox(height: 20), // 添加底部间距
          ],
        ),
      ),
    );
  }

  // 构建操作按钮（注册）
  Widget _buildActionButton(String text, VoidCallback onPressed) {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(28),
      ),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(28),
          ),
          padding: EdgeInsets.zero,
          elevation: 0,
        ),
        child: Text(
          text,
          style: const TextStyle(
            fontSize: 18,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}